package com.jrx.anytxn.param.job.investor.file.config;

import com.jrx.anytxn.common.uitl.DateUtils;
import com.jrx.anytxn.common.uitl.SftpUtils;
import com.jrx.anytxn.param.config.InvestorFileConfig;
import com.jrx.anytxn.param.config.SftpConfig;
import com.jrx.anytxn.param.constant.Constant;
import com.jrx.anytxn.param.dto.investor.SftpBean;
import com.jrx.anytxn.param.entity.PrOrganizationTable;
import com.jrx.anytxn.param.service.system.IOrganizationTableService;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.ArrayUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.batch.core.Job;
import org.springframework.batch.core.Step;
import org.springframework.batch.core.configuration.annotation.JobBuilderFactory;
import org.springframework.batch.core.configuration.annotation.StepBuilderFactory;
import org.springframework.batch.core.configuration.annotation.StepScope;
import org.springframework.batch.core.step.tasklet.Tasklet;
import org.springframework.batch.repeat.RepeatStatus;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.io.File;
import java.util.Arrays;
import java.util.List;

/**
 * @program: 联合贷文件上传
 * @description:
 * @author: xiaoyu.jing
 * @date: 2020-06-08 16:40
 **/
@Configuration
@EnableConfigurationProperties({SftpConfig.class})
public class InvestorFileUploadConfiguration {

    private static final Logger logger = LoggerFactory.getLogger(InvestorFileUploadConfiguration.class);


    @Autowired
    public JobBuilderFactory jobBuilderFactory;
    @Autowired
    public StepBuilderFactory stepBuilderFactory;
    @Autowired
    private SftpConfig sftpConfig;
    @Autowired
    private InvestorFileConfig InvestorFileConfig;
    @Autowired
    private IOrganizationTableService organizationTableService;

    @Bean
    public Job InvestorFileUploadJob() {
        return jobBuilderFactory.get("InvestorFileUploadJob")
                .start(InvestorFileUploadStep())
                .build();
    }

    @Bean
    public Step InvestorFileUploadStep() {
        return stepBuilderFactory.get("InvestorFileUploadStep")
                .tasklet(InvestorFileUploadTasklet())
                .build();
    }

    @Bean
    @StepScope
    public Tasklet InvestorFileUploadTasklet() {
        return (stepContribution, chunkContext) -> {
            logger.info("联合贷文件上传开始。。。。。。");

            String basePath = InvestorFileConfig.getInvestorFilePath();

            PrOrganizationTable org = organizationTableService.findByOrgIdForBatch(Constant.DEFAULT_ORG_NUMBER);
            String today = DateUtils.format(org.getToday(), "yyyyMMdd");

            List<SftpBean> sftpBeanList = sftpConfig.getSftpBeanList();
            if(CollectionUtils.isEmpty(sftpBeanList)){
                return RepeatStatus.FINISHED;
            }
            for (SftpBean sftpBean : sftpBeanList) {
                String investorId = sftpBean.getInvestorId();

                String filePath = basePath + File.separator + org.getTenantId() + File.separator + investorId + File.separator + today + File.separator;

                File file = new File(filePath);
                File[] tempList = file.listFiles();
                if(ArrayUtils.isEmpty(tempList)){
                    continue;
                }

                //1 获取连接
                SftpUtils.sftpConnect(sftpBean.getUsername(), sftpBean.getPassword(), sftpBean.getHost(), sftpBean.getPort());

                //2 检查创建目录
                String directory = sftpBean.getUploadPath() + File.separator + org.getTenantId() + File.separator + today;
                SftpUtils.createDir(directory);

                //3 先上传TXT文件，再上传OK文件
                //原文件不删除，按照文件名判断是否需要上传
                List<String> txtFileLists = Arrays.asList(Constant.DAY_ORDER_FILE_NAME + "_" + today + ".txt",
                        Constant.DAY_PLAN_FILE_NAME + "_" + today + ".txt",
                        Constant.LOAN_ORDER_FILE_NAME + "_" + today + ".txt",
                        Constant.LOAN_PLAN_FILE_NAME + "_" + today + ".txt",
                        Constant.REPAY_ORDER_FILE_NAME + "_" + today + ".txt",
                        Constant.REPAY_PLAN_FILE_NAME + "_" + today + ".txt",
                        Constant.TRANS_FILE_NAME + "_" + today + ".txt",
                        Constant.INTR_FILE_NAME + "_" + today + ".txt",
                        Constant.ACCOUNTING_FILE_NAME + "_" + today + ".txt",
                        Constant.GL_FILE_NAME + "_" + today + ".txt");
                for (File uploadFile : tempList) {
                    String filename = uploadFile.getName();
                    if (txtFileLists.contains(filename)) {
                        SftpUtils.sftpUpload(uploadFile);
                    }
                }
                logger.info("联合贷txt文件上传完成。。。。。。");
                String dataok = today + ".ok";
                List<String> okFileLists = Arrays.asList(Constant.DAY_ORDER_FILE_NAME + "_" + today + ".ok",
                        Constant.DAY_PLAN_FILE_NAME + "_" + today + ".ok",
                        Constant.LOAN_ORDER_FILE_NAME + "_" + today + ".ok",
                        Constant.LOAN_PLAN_FILE_NAME + "_" + today + ".ok",
                        Constant.REPAY_ORDER_FILE_NAME + "_" + today + ".ok",
                        Constant.REPAY_PLAN_FILE_NAME + "_" + today + ".ok",
                        Constant.TRANS_FILE_NAME + "_" + today + ".ok",
                        Constant.INTR_FILE_NAME + "_" + today + ".ok",
                        Constant.ACCOUNTING_FILE_NAME + "_" + today + ".txt",
                        Constant.GL_FILE_NAME + "_" + today + ".txt");
                for (File uploadFile : tempList) {
                    String filename = uploadFile.getName();
                    if (dataok.equals(filename)) {
                        continue;
                    }
                    if (okFileLists.contains(filename)) {
                        SftpUtils.sftpUpload(uploadFile);
                    }
                }
                logger.info("单个ok文件上传完成。。。。。。");

                for (File uploadFile : tempList) {
                    String filename = uploadFile.getName();
                    if (dataok.equals(filename)) {
                        SftpUtils.sftpUpload(uploadFile);
                        break;
                    }
                }
                logger.info("日期ok文件上传完成。。。。。。");

                //关闭连接
                SftpUtils.disSftpConnect();
            }

            logger.info("联合贷文件上传结束。。。。。。");
            return RepeatStatus.FINISHED;
        };
    }
}
